package com.mall.order.services;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mall.order.OrderQueryService;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.constants.OrderConstants;
import com.mall.order.converter.OrderConverter;
import com.mall.order.dal.entitys.*;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.OrderMapper;
import com.mall.order.dal.persistence.OrderShippingMapper;
import com.mall.order.dal.persistence.StockMapper;
import com.mall.order.dto.*;
import com.mall.order.utils.ExceptionProcessorUtils;
import com.mall.user.constants.SysRetCodeConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * cskaoyan
 */
@Slf4j
@Component
@Service
public class OrderQueryServiceImpl implements OrderQueryService {

    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderItemMapper orderItemMapper;
    @Autowired
    OrderShippingMapper orderShippingMapper;
    @Autowired
    OrderConverter orderConverter;


    /**
     * @description:
     * @param: 订单查询
     * @return:
     * @author zhizhuke
     * @date: 2022-01-20 16:41
     */
    @Override
    public OrderListResponse listOrder(OrderListRequest listRequest) {
        OrderListResponse listResponse = new OrderListResponse();

        try {
            listRequest.requestCheck();

            PageHelper.startPage(listRequest.getPage(), listRequest.getSize());
            Example exampleOrder = new Example(Order.class);
            if (listRequest.getSort() != null) {
                exampleOrder.setOrderByClause("create_time" + " " + listRequest.getSort());//todo /n
            }
            exampleOrder.createCriteria().andEqualTo("userId", listRequest.getUserId()).andNotEqualTo("status", -1);//-1 实现逻辑删除
            List<Order> orders = orderMapper.selectByExample(exampleOrder);
            PageInfo<Order> pageInfo = new PageInfo<>(orders);
            long total = pageInfo.getTotal();

            List<OrderDetailInfo> infoList = new ArrayList<>();
            for (Order order : orders) {
                //订单详情
                OrderDetailInfo orderDetailInfo = orderConverter.order2detail(order);

                //订单里面的商品详情
                Example exampleItem = new Example(OrderItem.class);
                exampleItem.createCriteria().andEqualTo("orderId", order.getOrderId());
                List<OrderItem> orderItems = orderItemMapper.selectByExample(exampleItem);
                List<OrderItemDto> orderItemDtos = orderConverter.item2dto(orderItems);

                orderDetailInfo.setOrderItemDto(orderItemDtos);

                //订单的物流信息
                OrderShipping orderShipping = orderShippingMapper.selectByPrimaryKey(order.getOrderId());
                OrderShippingDto orderShippingDto = orderConverter.shipping2dto(orderShipping);
                orderDetailInfo.setOrderShippingDto(orderShippingDto);

                infoList.add(orderDetailInfo);
            }
            OrderListDto orderListDto = new OrderListDto();
            orderListDto.setData(infoList);
            orderListDto.setTotal(total);
            listResponse.setOrderListDto(orderListDto);
            listResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
            listResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());

        } catch (Exception e) {
            log.error("OrderQueryServiceImpl.listOrder Occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(listResponse, e);
        }

        return listResponse;
    }

    OrderConstants orderConstants;
    @Override
    public OrderDetailResponseMy selectOrderDetail(OrderDetailRequest orderDetailRequest) {
        OrderDetailResponseMy orderDetailResponseMy = new OrderDetailResponseMy();
        try {
            //校验参数的合法性
            orderDetailRequest.requestCheck();
//            //进行订单详情查询
            Order order = orderMapper.selectByPrimaryKey(orderDetailRequest.getOrderId());
//            进行订单包含商品的详情查询
            Example example = new Example(OrderItem.class);
            example.createCriteria().andEqualTo("orderId", orderDetailRequest.getOrderId());
            List<OrderItem> orderItems = orderItemMapper.selectByExample(example);
            //进行订单包含shipping的详情查询
            OrderShipping orderShipping = orderShippingMapper.selectByPrimaryKey(orderDetailRequest.getOrderId());
            // 封装Response中的order信息
            orderDetailResponseMy.setOrderStatus(order.getStatus());
            orderDetailResponseMy.setUserId(Math.toIntExact(order.getUserId()));
            orderDetailResponseMy.setUserName(order.getBuyerNick());
            BigDecimal bigDecimal = new BigDecimal(Double.toString(0));
            List<OrderDetailResponseMy.GoodsListDTO> goodsListDTOS = new ArrayList<>();
            for (OrderItem orderItem : orderItems) {
                bigDecimal = bigDecimal.add(BigDecimal.valueOf(orderItem.getTotalFee()));
                OrderDetailResponseMy.GoodsListDTO goodsListDTO = new OrderDetailResponseMy.GoodsListDTO();
                goodsListDTO.setId(orderItem.getId());
                goodsListDTO.setItemId(String.valueOf(orderItem.getItemId()));
                goodsListDTO.setNum(orderItem.getNum());
                goodsListDTO.setOrderId(orderItem.getOrderId());
                goodsListDTO.setPicPath(orderItem.getPicPath());
                goodsListDTO.setPrice(Integer.valueOf(orderItem.getPrice().intValue()));
                goodsListDTO.setTitle(orderItem.getTitle());
                goodsListDTO.setTotalFee(Integer.valueOf(orderItem.getTotalFee().intValue()));
                goodsListDTOS.add(goodsListDTO);
            }
            orderDetailResponseMy.setGoodsList(goodsListDTOS);
            orderDetailResponseMy.setOrderTotal(bigDecimal);
            orderDetailResponseMy.setStreetName(orderShipping.getReceiverAddress());
            orderDetailResponseMy.setTel(orderShipping.getReceiverPhone());

            orderDetailResponseMy.setCode(SysRetCodeConstants.SUCCESS.getCode());
            orderDetailResponseMy.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        } catch (Exception e) {
            //查询失败and参数校验失败 -> 抛出异常
            log.error("OrderQueryServiceImpl.selectOrderDetail occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(orderDetailResponseMy, e);
        }
        return orderDetailResponseMy;
    }
     @Autowired
     StockMapper stockMapper;
    @Override
    public CancelOrderResponse cancelOrder(CancelOrderRequest cancelOrderRequest) {
        CancelOrderResponse cancelOrderResponse = new CancelOrderResponse();
        try {
            //校验参数的合法性
            cancelOrderRequest.requestCheck();
            //进行订单详情查询
            Order order = new Order();
            order.setOrderId(cancelOrderRequest.getOrderId());
            order.setStatus(orderConstants.ORDER_STATUS_TRANSACTION_CANCEL);
            order.setUpdateTime(new Date());
            orderMapper.updateByPrimaryKeySelective(order);

            //进行订单item表的状态还原
            orderItemMapper.updateStockStatus(2,cancelOrderRequest.getOrderId());
            //进行订单库存还原
            Example example = new Example(OrderItem.class);
            example.createCriteria().andEqualTo("orderId",cancelOrderRequest.getOrderId());
            List<OrderItem> orderItems = orderItemMapper.selectByExample(example);
            for (OrderItem orderItem : orderItems) {
                Stock stock = new Stock();
                stock.setItemId(orderItem.getItemId());
                stock.setLockCount( - orderItem.getNum());
                stock.setStockCount(Long.valueOf(orderItem.getNum()));
                stockMapper.updateStock(stock);
            }


            cancelOrderResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
            cancelOrderResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());

        } catch (Exception e) {
            log.error("OrderQueryServiceImpl.cancelOrder occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(cancelOrderResponse, e);
        }
        return cancelOrderResponse;
    }


    @Override
    public DeleteOrderResponse deleteOrder(DeleteOrderRequest deleteOrderRequest) {
        DeleteOrderResponse deleteOrderResponse = new DeleteOrderResponse();
        try {
            //校验参数的合法性
            deleteOrderRequest.requestCheck();
            //进行订单逻辑删除操作
            Order order = new Order();
            order.setOrderId(deleteOrderRequest.getOrderId());
            order.setStatus(orderConstants.ORDER_STATUS_TRANSACTION_DELETE);
            order.setUpdateTime(new Date());
            orderMapper.updateByPrimaryKeySelective(order);
            deleteOrderResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
            deleteOrderResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        } catch (Exception e) {
            log.error("OrderQueryServiceImpl.deleteOrder occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(deleteOrderResponse, e);
        }
        return deleteOrderResponse;
    }

}
